<template>
  <div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item :label="$t('shift_name')" prop="cycleName">
        <el-input
          v-model="queryParams.cycleName"
          :placeholder="$t('please_enter', { name: $t('shift_name') })"
          :show-word-limit="true"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="所属雇主" prop="employerId">
        <employerSelect
          ref="employerSelect"
          v-model="queryParams.employerId"
          @setEmployerAllList="setEmployerAllList"
        >
        </employerSelect>
      </el-form-item> -->
      <el-form-item :label="$t('publisher')" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          :placeholder="$t('please_enter', { name: $t('publisher') })"
          :show-word-limit="true"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >{{ $t("search") }}</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("reset")
        }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >{{ $t("add_new_cycle_shift") }}</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="cycleList"
      @selection-change="handleSelectionChange"
      border
      :max-height="tableHeight"
    >
      <el-table-column
        :label="$t('cycle_shift_name')"
        align="center"
        prop="cycleName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="$t('shift_code')"
        align="center"
        prop="cycleCode"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column
        label="所属雇主"
        align="center"
        prop="employerId"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <dict-tag :options="employerAllList" :value="scope.row.employerId" />
        </template>
      </el-table-column> -->
      <el-table-column
        :label="$t('shift_combination')"
        align="center"
        prop="shiftGroup"
      >
        <template
          slot-scope="scope"
          v-if="scope.row.shiftDTOList && scope.row.shiftDTOList.length"
        >
          <div v-for="(item, index) in scope.row.shiftDTOList" :key="index">
            <span v-if="item">
              {{ item.shiftName }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('remarks')"
        align="center"
        prop="remark"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="$t('last_modification_time')"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('publisher')"
        align="center"
        prop="publisher"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="$t('action')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            >{{ $t("view") }}</el-button
          >
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['cycle:cycle:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      :page-sizes="[10,20,30,50,100, 200]"
    />

    <!-- 添加或修改周期班对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="lookView"
      >
        <!-- <el-form-item label="选择雇主" prop="employerId">
          <employerSelect v-model="form.employerId"></employerSelect>
        </el-form-item> -->
        <el-form-item :label="$t('shift_name')" prop="cycleName">
          <el-input
            v-model="form.cycleName"
            :placeholder="$t('please_enter', { name: $t('shift_name') })"
          />
        </el-form-item>
        <el-form-item :label="$t('shift_code')" prop="cycleCode">
          <el-input
            v-model="form.cycleCode"
            :placeholder="$t('please_enter', { name: $t('shift_code') })"
          />
        </el-form-item>
        <template v-if="lookView">
          <el-form-item :label="$t('selected_shift')">
            <template v-if="form.shiftDTOList">
              <span
                style="margin: 0 16px 16px 0"
                v-for="(item, index) in form.shiftDTOList"
                :key="index"
              >
                {{ item.shiftName }}
              </span>
            </template>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item :label="$t('select_shift')">
            <el-button type="primary" @click="checkClasses">{{
              $t("select_shift")
            }}</el-button>
          </el-form-item>
          <el-form-item
            :label="$t('selected_shift')"
            v-if="checkClassesList.length"
          >
            <el-tag
              :key="index"
              v-for="(item, index) in checkClassesList"
              closable
              :disable-transitions="false"
              @close="handleRemoveClasses(index)"
              style="margin-right: 10px"
            >
              {{ item.shiftName }}
            </el-tag>
          </el-form-item>
        </template>

        <el-form-item :label="$t('remarks')" prop="remark">
          <el-input
            v-model="form.remark"
            :placeholder="$t('please_enter', { name: $t('remarks') })"
            type="textarea"
            rows="4"
            :show-word-limit="true"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!lookView">
        <el-button type="primary" @click="submitForm">{{
          $t("confirm")
        }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="$t('select_shift')"
      :visible.sync="classesOpen"
      width="800px"
      append-to-body
    >
      <classesRecord
        ref="classesRecord"
        :showOption="false"
        :isSelect="true"
        :checkClassesList="checkClassesList"
        @handleSelectionClasses="selectClasses"
        v-if="classesOpen"
      ></classesRecord>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCycle,
  getCycle,
  delCycle,
  addCycle,
  updateCycle,
} from "@/api/checkWork/cycle.js";
import classesRecord from "./classesRecord.vue";
import employerSelect from "@/views/components/custom/employerSelect.vue";
export default {
  name: "Cycle",
  components: {
    classesRecord,
    employerSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 周期班表格数据
      cycleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // employerId: null,
        cycleName: null,
        createBy: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // employerId: [
        //   {
        //     required: true,
        //     message: "所属雇主不能为空",
        //     trigger: "change",
        //   },
        // ],
        cycleName: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("shift_name") }),
            trigger: "blur",
          },
        ],
        cycleCode: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("shift_code") }),
            trigger: "blur",
          },
        ],
      },
      employerAllList: [],
      classesOpen: false,
      checkClassesList: [],
      lookView: false,
    };
  },
  created() {
    this.getList();
  },
  mounted() {},
  methods: {
    /** 查询周期班列表 */
    getList() {
      this.loading = true;
      listCycle(this.queryParams).then((response) => {
        this.cycleList = response.data.records.map((item) => {
          item.classesArr = item.shiftGroup && item.shiftGroup.split(",");
          return item;
        });
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        // employerId: null,
        cycleName: null,
        cycleCode: null,
        remark: null,
        shiftGroup: null,
      };
      this.checkClassesList = [];
      this.lookView = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t("add");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCycle(id).then((response) => {
        response.data.shiftGroup =
          response.data.shiftGroup && response.data.shiftGroup.split(",");
        this.form = response.data.records;
        this.open = true;
        this.title = this.$t("modify");
      });
    },
    handleView(row) {
      this.reset();
      this.form = {
        ...row,
      };
      this.open = true;
      this.lookView = true;
      this.title = this.$t("view");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        console.log(this.form);
        if (valid) {
          if (this.checkClassesList.length) {
            this.form.shiftGroup = this.checkClassesList
              .map((item) => item.id)
              .join(",");
          } else {
            this.$modal.msgError(
              this.$t("please_select", { name: this.$t("shift") })
            );
            return;
          }
          if (this.form.id != null) {
            updateCycle(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.open = false;
              this.getList();
            });
          } else {
            addCycle(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("operation_successful"));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(this.$t("delete_data"))
        .then(function () {
          return delCycle(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("operation_successful"));
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "cycle/cycle/export",
        {
          ...this.queryParams,
        },
        `cycle_${new Date().getTime()}.xlsx`
      );
    },
    setEmployerAllList(list) {
      this.employerAllList = list.map((item) => {
        return {
          ...item,
          value: item.value.toString(),
        };
      });
    },
    checkClasses() {
      this.classesOpen = true;
    },
    selectClasses(row) {
      console.log(row);
      this.checkClassesList.push(row);
      this.classesOpen = false;
    },
    handleRemoveClasses(index) {
      this.checkClassesList.splice(index, 1);
    },
  },
};
</script>
